package com.qiwenshare.file.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.qiwenshare.common.anno.MyLog;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.MimeUtils;
import com.qiwenshare.common.util.security.JwtUser;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.api.IFileService;
import com.qiwenshare.file.api.IFiletransferService;
import com.qiwenshare.file.api.IOperationLogService;
import com.qiwenshare.file.api.IUserFileService;
import com.qiwenshare.file.component.FileDealComp;
import com.qiwenshare.file.domain.FileBean;
import com.qiwenshare.file.domain.OperationLogBean;
import com.qiwenshare.file.domain.StorageBean;
import com.qiwenshare.file.domain.UserFile;
import com.qiwenshare.file.dto.file.BatchDownloadFileDTO;
import com.qiwenshare.file.dto.file.DownloadFileDTO;
import com.qiwenshare.file.dto.file.PreviewDTO;
import com.qiwenshare.file.dto.file.UploadFileDTO;
import com.qiwenshare.file.io.QiwenFile;
import com.qiwenshare.file.mapper.FileMapper;
import com.qiwenshare.file.mapper.ImageMapper;
import com.qiwenshare.file.mapper.UserFileMapper;
import com.qiwenshare.file.service.StorageService;
import com.qiwenshare.file.util.FastJsonUtil;
import com.qiwenshare.file.util.FileUploadUtils;
import com.qiwenshare.file.vo.file.UploadFileVo;
import com.qiwenshare.ufop.factory.UFOPFactory;
import com.qiwenshare.ufop.operation.download.Downloader;
import com.qiwenshare.ufop.operation.download.domain.DownloadFile;
import com.qiwenshare.ufop.operation.download.domain.Range;
import com.qiwenshare.ufop.util.UFOPUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
import javax.transaction.Transactional;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.qiwenshare.file.util.FileUploadUtils.checkFileExt;
import static com.qiwenshare.file.util.FileUploadUtils.propertyUtil;

@Slf4j
@Tag(name = "filetransfer", description = "该接口为文件传输接口，主要用来做文件的上传、下载和预览")
@RestController
@RequestMapping("/filetransfer")
public class FiletransferController {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private UserFileMapper userFileMapper;
    @Resource
    IFiletransferService filetransferService;

    @Resource
    IFileService fileService;
    @Resource
    IUserFileService userFileService;
    @Resource
    FileDealComp fileDealComp;
    @Resource
    StorageService storageService;
    @Resource
    UFOPFactory ufopFactory;
    @Resource
    IOperationLogService operationLogService;

    public static final String CURRENT_MODULE = "文件传输接口";
    //商品系统上传下载路径
    public static final String projectPath = "D:/swq/release/static/";

    // private static  String userFileIds="";//用户上传的文件名集合
    //private  static  String  fileSuffixs="";//文件后缀名 集合
    @Operation(summary = "极速上传", description = "校验文件MD5判断文件是否存在，如果存在直接上传成功并返回skipUpload=true，如果不存在返回skipUpload=false需要再次调用该接口的POST方法", tags = {"filetransfer"})
    @RequestMapping(value = "/uploadfile", method = RequestMethod.GET)
    @MyLog(operation = "极速上传", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UploadFileVo> uploadFileSpeed(UploadFileDTO uploadFileDto) {
        //上传类型
        String uploadType = uploadFileDto.getUploadType();
        System.out.println("上传类型:" + uploadType);
        JwtUser sessionUserBean = SessionUtil.getSession();
        boolean isCheckSuccess = storageService.checkStorage(SessionUtil.getUserId(), uploadFileDto.getTotalSize());
        if (!isCheckSuccess) {
            return RestResult.fail().message("存储空间不足");
        }
        UploadFileVo uploadFileVo = filetransferService.uploadFileSpeed(uploadFileDto, uploadType);//swq23111 上传类型 1：私人；2：公共
        return RestResult.success().data(uploadFileVo);
    }

    @Operation(summary = "上传文件", description = "真正的上传文件接口", tags = {"filetransfer"})
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    @MyLog(operation = "上传文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UploadFileVo> uploadFile(HttpServletRequest request, UploadFileDTO uploadFileDto) {
        //上传类型
        String uploadType = uploadFileDto.getUploadType();
        System.out.println("上传类型:" + uploadType);

        JwtUser sessionUserBean = SessionUtil.getSession();
        filetransferService.uploadFile(request, uploadFileDto, sessionUserBean.getUserId(), uploadType);//swq23111 上传类型 1：私人；2：公共
        UploadFileVo uploadFileVo = new UploadFileVo();
        return RestResult.success().data(uploadFileVo);
    }


    @Operation(summary = "极速上传", description = "校验文件MD5判断文件是否存在，如果存在直接上传成功并返回skipUpload=true，如果不存在返回skipUpload=false需要再次调用该接口的POST方法", tags = {"filetransfer"})
    @RequestMapping(value = "/uploadfileAll", method = RequestMethod.GET)
    @MyLog(operation = "极速上传", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UploadFileVo> uploadFileSpeedAll(UploadFileDTO uploadFileDto) {
        JwtUser sessionUserBean = SessionUtil.getSession();
        boolean isCheckSuccess = storageService.checkStorage(SessionUtil.getUserId(), uploadFileDto.getTotalSize());
        if (!isCheckSuccess) {
            return RestResult.fail().message("存储空间不足");
        }
        UploadFileVo uploadFileVo = filetransferService.uploadFileSpeed(uploadFileDto, "2");//swq23111 上传类型 1：私人；2：公共
        return RestResult.success().data(uploadFileVo);
    }


    @Operation(summary = "上传文件", description = "真正的上传文件接口", tags = {"filetransfer"})
    @RequestMapping(value = "/uploadfileAll", method = RequestMethod.POST)
    @MyLog(operation = "上传文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<UploadFileVo> uploadFileAll(HttpServletRequest request, UploadFileDTO uploadFileDto) {

        JwtUser sessionUserBean = SessionUtil.getSession();
        filetransferService.uploadFile(request, uploadFileDto, sessionUserBean.getUserId(), "2");//swq23111 上传类型 1：私人；2：公共
        UploadFileVo uploadFileVo = new UploadFileVo();
        return RestResult.success().data(uploadFileVo);
    }


    @Operation(summary = "下载文件", description = "下载文件接口", tags = {"filetransfer"})
    @MyLog(operation = "下载文件", module = CURRENT_MODULE)
    @RequestMapping(value = "/downloadfile", method = RequestMethod.GET)
    public void downloadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, DownloadFileDTO downloadFileDTO) {
        Cookie[] cookieArr = httpServletRequest.getCookies();
        String token = "";
        if (cookieArr != null) {
            for (Cookie cookie : cookieArr) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        boolean authResult = fileDealComp.checkAuthDownloadAndPreview(downloadFileDTO.getShareBatchNum(),
                downloadFileDTO.getExtractionCode(),
                token,
                downloadFileDTO.getUserFileId(), null);
        if (!authResult) {
            log.error("没有权限下载！！！");
            return;
        }
        httpServletResponse.setContentType("application/force-download");// 设置强制下载不打开
        UserFile userFile = userFileService.getById(downloadFileDTO.getUserFileId());
        String fileName = "";
        if (userFile.getIsDir() == 1) {
            fileName = userFile.getFileName() + ".zip";
        } else {
            fileName = userFile.getFileName() + "." + userFile.getExtendName();

        }
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        downloadFileDTO.setUploadType(userFile.getUploadType());//swq231120
        httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        filetransferService.downloadFile(httpServletResponse, downloadFileDTO);
    }

    //swq231111
    @Operation(summary = "下载文件", description = "下载文件接口", tags = {"filetransfer"})
    @MyLog(operation = "下载文件", module = CURRENT_MODULE)
    @RequestMapping(value = "/downloadfileAll", method = RequestMethod.GET)
    public void downloadFileAll(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, DownloadFileDTO downloadFileDTO) {
        Cookie[] cookieArr = httpServletRequest.getCookies();
        String token = "";
        if (cookieArr != null) {
            for (Cookie cookie : cookieArr) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        boolean authResult = fileDealComp.checkAuthDownloadAndPreview(downloadFileDTO.getShareBatchNum(),
                downloadFileDTO.getExtractionCode(),
                token,
                downloadFileDTO.getUserFileId(), null);
        if (!authResult) {
            log.error("没有权限下载！！！");
            return;
        }
        httpServletResponse.setContentType("application/force-download");// 设置强制下载不打开
        UserFile userFile = userFileService.getById(downloadFileDTO.getUserFileId());
        String fileName = "";
        if (userFile.getIsDir() == 1) {
            fileName = userFile.getFileName() + ".zip";
        } else {
            fileName = userFile.getFileName() + "." + userFile.getExtendName();

        }
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        downloadFileDTO.setUploadType(userFile.getUploadType());//swq231120
        httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        filetransferService.downloadFile(httpServletResponse, downloadFileDTO);
    }


    @Operation(summary = "批量下载文件", description = "批量下载文件", tags = {"filetransfer"})
    @RequestMapping(value = "/batchDownloadFile", method = RequestMethod.GET)
    @MyLog(operation = "批量下载文件", module = CURRENT_MODULE)
    @ResponseBody
    public void batchDownloadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BatchDownloadFileDTO batchDownloadFileDTO) {
        Cookie[] cookieArr = httpServletRequest.getCookies();
        String token = "";
        if (cookieArr != null) {
            for (Cookie cookie : cookieArr) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
      /*  boolean authResult = fileDealComp.checkAuthDownloadAndPreview(batchDownloadFileDTO.getShareBatchNum(),
                batchDownloadFileDTO.getExtractionCode(),
                token,
                batchDownloadFileDTO.getUserFileIds(), null);
        if (!authResult) {
            log.error("没有权限下载！！！");
            return;
        }*/

        String files = batchDownloadFileDTO.getUserFileIds();
        String[] userFileIdStrs = files.split(",");
        List<String> userFileIds = new ArrayList<>();
        for (String userFileId : userFileIdStrs) {
            UserFile userFile = userFileService.getById(userFileId);
            if (userFile.getIsDir() == 0) {
                userFileIds.add(userFileId);
            } else {
                userFile.setUserId("");//swq231121 置空包含全部文件
                QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                List<UserFile> userFileList = userFileService.selectUserFileByLikeRightFilePath(qiwenFile.getPath(), userFile.getUserId(), userFile.getUploadType());//swq231120UploadType
                List<String> userFileIds1 = userFileList.stream().map(UserFile::getUserFileId).collect(Collectors.toList());
                userFileIds.add(userFile.getUserFileId());
                userFileIds.addAll(userFileIds1);
            }

        }
        UserFile userFile = userFileService.getById(userFileIdStrs[0]);
        httpServletResponse.setContentType("application/force-download");// 设置强制下载不打开
        Date date = new Date();
        String fileName = String.valueOf(date.getTime());
        httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");// 设置文件名
        filetransferService.downloadUserFileList(httpServletResponse, userFile.getFilePath(), fileName, userFileIds);
    }


    //swq231111
    @Operation(summary = "批量下载文件", description = "批量下载文件", tags = {"filetransfer"})
    @RequestMapping(value = "/batchDownloadFileAll", method = RequestMethod.GET)
    @MyLog(operation = "批量下载文件", module = CURRENT_MODULE)
    @ResponseBody
    public void batchDownloadFileAll(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BatchDownloadFileDTO batchDownloadFileDTO) {
        Cookie[] cookieArr = httpServletRequest.getCookies();
        String token = "";
        if (cookieArr != null) {
            for (Cookie cookie : cookieArr) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
     /*   boolean authResult = fileDealComp.checkAuthDownloadAndPreview(batchDownloadFileDTO.getShareBatchNum(),
                batchDownloadFileDTO.getExtractionCode(),
                token,
                batchDownloadFileDTO.getUserFileIds(), null);
        if (!authResult) {
            log.error("没有权限下载！！！");
            return;
        }*/

        String files = batchDownloadFileDTO.getUserFileIds();
        String[] userFileIdStrs = files.split(",");
        List<String> userFileIds = new ArrayList<>();
        for (String userFileId : userFileIdStrs) {
            UserFile userFile = userFileService.getById(userFileId);
            if (userFile.getIsDir() == 0) {
                userFileIds.add(userFileId);
            } else {
                userFile.setUserId("");//swq231121 置空包含全部文件
                QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                List<UserFile> userFileList = userFileService.selectUserFileByLikeRightFilePath(qiwenFile.getPath(), userFile.getUserId(), userFile.getUploadType());//swq231120
                List<String> userFileIds1 = userFileList.stream().map(UserFile::getUserFileId).collect(Collectors.toList());
                userFileIds.add(userFile.getUserFileId());
                userFileIds.addAll(userFileIds1);
            }

        }
        UserFile userFile = userFileService.getById(userFileIdStrs[0]);
        httpServletResponse.setContentType("application/force-download");// 设置强制下载不打开
        Date date = new Date();
        String fileName = String.valueOf(date.getTime());
        httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");// 设置文件名
        filetransferService.downloadUserFileList(httpServletResponse, userFile.getFilePath(), fileName, userFileIds);
    }


    @Operation(summary = "预览文件", description = "用于文件预览", tags = {"filetransfer"})
    @GetMapping("/preview")
    public void preview(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, PreviewDTO previewDTO) throws IOException {

        if (previewDTO.getPlatform() != null && previewDTO.getPlatform() == 2) {
            filetransferService.previewPictureFile(httpServletResponse, previewDTO);
            return;
        }
        String token = "";
        if (StringUtils.isNotEmpty(previewDTO.getToken())) {
            token = previewDTO.getToken();
        } else {
            Cookie[] cookieArr = httpServletRequest.getCookies();
            if (cookieArr != null) {
                for (Cookie cookie : cookieArr) {
                    if ("token".equals(cookie.getName())) {
                        token = cookie.getValue();
                    }
                }
            }
        }

        UserFile userFile = userFileService.getById(previewDTO.getUserFileId());
       /* boolean authResult = fileDealComp.checkAuthDownloadAndPreview(previewDTO.getShareBatchNum(),
                previewDTO.getExtractionCode(),
                token,
                previewDTO.getUserFileId(),
                previewDTO.getPlatform());

        if (!authResult) {
            log.error("没有权限预览！！！");
            return;
        }*/

        String fileName = userFile.getFileName() + "." + userFile.getExtendName();
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        httpServletResponse.addHeader("Content-Disposition", "fileName=" + fileName);// 设置文件名
        String mime = MimeUtils.getMime(userFile.getExtendName());
        httpServletResponse.setHeader("Content-Type", mime);
        if (UFOPUtils.isImageFile(userFile.getExtendName())) {
            httpServletResponse.setHeader("cache-control", "public");
        }

        FileBean fileBean = fileService.getById(userFile.getFileId());
        if (UFOPUtils.isVideoFile(userFile.getExtendName()) || "mp3".equalsIgnoreCase(userFile.getExtendName()) || "flac".equalsIgnoreCase(userFile.getExtendName())) {
            //获取从那个字节开始读取文件
            String rangeString = httpServletRequest.getHeader("Range");
            int start = 0;
            if (StringUtils.isNotBlank(rangeString)) {
                start = Integer.parseInt(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
            }

            Downloader downloader = ufopFactory.getDownloader(fileBean.getStorageType());
            DownloadFile downloadFile = new DownloadFile();
            downloadFile.setFileUrl(fileBean.getFileUrl());
            Range range = new Range();
            range.setStart(start);

            if (start + 1024 * 1024 * 1 >= fileBean.getFileSize().intValue()) {
                range.setLength(fileBean.getFileSize().intValue() - start);
            } else {
                range.setLength(1024 * 1024 * 1);
            }
            downloadFile.setRange(range);
            InputStream inputStream = downloader.getInputStream(downloadFile);

            OutputStream outputStream = httpServletResponse.getOutputStream();
            try {

                //返回码需要为206，代表只处理了部分请求，响应了部分数据

                httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                // 每次请求只返回1MB的视频流

                httpServletResponse.setHeader("Accept-Ranges", "bytes");
                //设置此次相应返回的数据范围
                httpServletResponse.setHeader("Content-Range", "bytes " + start + "-" + (fileBean.getFileSize() - 1) + "/" + fileBean.getFileSize());
                IOUtils.copy(inputStream, outputStream);


            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
                if (downloadFile.getOssClient() != null) {
                    downloadFile.getOssClient().shutdown();
                }
            }
        } else {
            filetransferService.previewFile(httpServletResponse, previewDTO);
        }
    }

    //swq231111
    @Operation(summary = "预览文件", description = "用于文件预览", tags = {"filetransfer"})
    @GetMapping("/previewAll")
    public void previewAll(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, PreviewDTO previewDTO) throws IOException {

        if (previewDTO.getPlatform() != null && previewDTO.getPlatform() == 2) {
            filetransferService.previewPictureFile(httpServletResponse, previewDTO);
            return;
        }
        String token = "";
        if (StringUtils.isNotEmpty(previewDTO.getToken())) {
            token = previewDTO.getToken();
        } else {
            Cookie[] cookieArr = httpServletRequest.getCookies();
            if (cookieArr != null) {
                for (Cookie cookie : cookieArr) {
                    if ("token".equals(cookie.getName())) {
                        token = cookie.getValue();
                    }
                }
            }
        }

        UserFile userFile = userFileService.getById(previewDTO.getUserFileId());
      /*   boolean authResult = fileDealComp.checkAuthDownloadAndPreview(previewDTO.getShareBatchNum(),
                previewDTO.getExtractionCode(),
                token,
                previewDTO.getUserFileId(),
                previewDTO.getPlatform());

        if (!authResult) {
            log.error("没有权限预览！！！");
            return;
        }*/

        String fileName = userFile.getFileName() + "." + userFile.getExtendName();
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        httpServletResponse.addHeader("Content-Disposition", "fileName=" + fileName);// 设置文件名
        String mime = MimeUtils.getMime(userFile.getExtendName());
        httpServletResponse.setHeader("Content-Type", mime);
        if (UFOPUtils.isImageFile(userFile.getExtendName())) {
            httpServletResponse.setHeader("cache-control", "public");
        }

        FileBean fileBean = fileService.getById(userFile.getFileId());
        if (UFOPUtils.isVideoFile(userFile.getExtendName()) || "mp3".equalsIgnoreCase(userFile.getExtendName()) || "flac".equalsIgnoreCase(userFile.getExtendName())) {
            //获取从那个字节开始读取文件
            String rangeString = httpServletRequest.getHeader("Range");
            int start = 0;
            if (StringUtils.isNotBlank(rangeString)) {
                start = Integer.parseInt(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
            }

            Downloader downloader = ufopFactory.getDownloader(fileBean.getStorageType());
            DownloadFile downloadFile = new DownloadFile();
            downloadFile.setFileUrl(fileBean.getFileUrl());
            Range range = new Range();
            range.setStart(start);

            if (start + 1024 * 1024 * 1 >= fileBean.getFileSize().intValue()) {
                range.setLength(fileBean.getFileSize().intValue() - start);
            } else {
                range.setLength(1024 * 1024 * 1);
            }
            downloadFile.setRange(range);
            InputStream inputStream = downloader.getInputStream(downloadFile);

            OutputStream outputStream = httpServletResponse.getOutputStream();
            try {

                //返回码需要为206，代表只处理了部分请求，响应了部分数据

                httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                // 每次请求只返回1MB的视频流

                httpServletResponse.setHeader("Accept-Ranges", "bytes");
                //设置此次相应返回的数据范围
                httpServletResponse.setHeader("Content-Range", "bytes " + start + "-" + (fileBean.getFileSize() - 1) + "/" + fileBean.getFileSize());
                IOUtils.copy(inputStream, outputStream);


            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
                if (downloadFile.getOssClient() != null) {
                    downloadFile.getOssClient().shutdown();
                }
            }
        } else {
            filetransferService.previewFile(httpServletResponse, previewDTO);
        }
    }


    @Operation(summary = "获取存储信息", description = "获取存储信息", tags = {"filetransfer"})
    @RequestMapping(value = "/getstorage", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<StorageBean> getStorage() {
        JwtUser sessionUserBean = SessionUtil.getSession();
        StorageBean storageBean = new StorageBean();

        storageBean.setUserId(sessionUserBean.getUserId());
        Long storageSize = filetransferService.selectStorageSizeByUserId(sessionUserBean.getUserId());
        StorageBean storage = new StorageBean();
        storage.setUserId(sessionUserBean.getUserId());
        storage.setStorageSize(storageSize);
        Long totalStorageSize = storageService.getTotalStorageSize(sessionUserBean.getUserId());
        storage.setTotalStorageSize(totalStorageSize);
        return RestResult.success().data(storage);
    }

    //swq231111
    @Operation(summary = "获取存储信息", description = "获取存储信息", tags = {"filetransfer"})
    @RequestMapping(value = "/getstorageAll", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<StorageBean> getStorageAll() {

        JwtUser sessionUserBean = SessionUtil.getSession();
        StorageBean storageBean = new StorageBean();
        storageBean.setUserId(sessionUserBean.getUserId());
        Long storageSize = filetransferService.selectStorageSizeByUserId(sessionUserBean.getUserId());
        StorageBean storage = new StorageBean();
        storage.setUserId(sessionUserBean.getUserId());
        storage.setStorageSize(storageSize);
        Long totalStorageSize = storageService.getTotalStorageSize(sessionUserBean.getUserId());
        storage.setTotalStorageSize(totalStorageSize);
        return RestResult.success().data(storage);
    }


    /////////////////////////////swq231109///////////////////////////
    private static String getProjectRootDirPath() {
        return propertyUtil.getProperty("file.root");
    }

    @RequestMapping(value = "/uploadfile1")
    @ResponseBody
    public String uploadfile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "param", required = false) String param) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile("fileupload");
            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
            if ("jsp".equalsIgnoreCase(ext) || "php".equalsIgnoreCase(ext) || "asp".equalsIgnoreCase(ext)) {
                //return responseData("",1,"文件格式错误，上传失败");
                System.out.println("文件格式错误，上传失败");
                return responseErrorData(response, 1, "文件格式错误，上传失败。");
            }
            //获取文件路径
            String filePath = getPath(request, ext, param);
            File file = new File(getProjectRootDirPath() + filePath);

            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //保存文件
            imgFile.transferTo(file);

            System.out.println("++++upload img return:" + filePath);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("url", filePath);
            map.put("fileName", imgFile.getOriginalFilename());
            return FastJsonUtil.obj2JsonString(map);
        } catch (Exception e) {
            System.out.println("uploadfile error" + e);
        }
        return null;
    }

    public String responseErrorData(HttpServletResponse response, int error, String message) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("error", error);
            map.put("message", message);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().print(FastJsonUtil.obj2JsonString(map));
            response.getWriter().flush();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }

    private String getPath(HttpServletRequest request, String ext, String param) {
        String filePath = "upload";
        if (param != null && param.trim().length() > 0) {
            filePath += param;
        } //else{
        //   filePath+= propertyUtil.getProperty("projectName");
        //  }
        filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + "." + ext;
        return filePath;
    }

    public static String toString(Date date, String pattern) {
        if (date == null) {
            return "";
        } else {
            if (pattern == null) {
                pattern = "yyyy-MM-dd";
            }

            String dateString = "";
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);

            try {
                dateString = sdf.format(date);
            } catch (Exception var5) {
                var5.printStackTrace();
            }

            return dateString;
        }
    }

    /*
     * 图片缩放,w，h为缩放的目标宽度和高度
     * src为源文件目录
     */
    public static void zoomImage(String src, int newWidth, int newHeight) throws Exception {
        if (newWidth == 0 || newHeight == 0 || src == null || src.trim().length() == 0) {
            return;
        }
        String dest = getProjectRootDirPath();

        BufferedImage result = null;
        try {
            File f2 = new File(dest + src);

            BufferedImage bi2 = ImageIO.read(f2);
            int originalh = bi2.getHeight();
            int originalw = bi2.getWidth();

            if (originalh != newHeight && originalw != newWidth) {
                BufferedImage to = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

                Graphics2D g2d = to.createGraphics();

                to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight,

                        Transparency.TRANSLUCENT);

                g2d.dispose();

                g2d = to.createGraphics();

                Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING);
                g2d.drawImage(from, 0, 0, null);
                g2d.dispose();
                ImageIO.write(to, "png", new File(dest + src));
            }
        } catch (Exception e) {
            System.out.println("创建缩略图发生异常" + e.getMessage());
        }
    }


    @RequestMapping(value = "/keupload", method = {RequestMethod.POST})
    public String kindEditorUpload(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "param", required = false) String param,
                                   @RequestParam(value = "pressText", required = false) String pressText) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile("imgFile");
            if (imgFile == null) {
                System.out.println("请选择上传的文件，上传失败");
                return responseData("", 1, "请选择上传的文件，上传失败", response);
            }
            //最大文件大小
            long maxSize = 4096000;
            //logger.info(imgFile.getSize());
            //检查文件大小
            if (imgFile.getSize() > maxSize) {
                System.out.println("上传的图片大小不能超过4M");
                return responseErrorData(response, 1, "上传的图片大小不能超过4M。");
            }

            //获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
            String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
            if (!checkFileExt(ext)) {
                System.out.println("文件格式错误，上传失败");
                return responseErrorData(response, 1, "文件格式错误，上传失败。");
            }
            //获取文件路径
            String filePath = getPath(request, ext, param);
            File file = new File(getProjectRootDirPath() + filePath);

            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //保存文件
            imgFile.transferTo(file);
            //上水印
//			if(pressText!=null && pressText.equals("true")){
//				FileUploadUtils.pressText("inxedu", file.getPath(), file.getPath(), "Segoe Script", Font.BOLD, Color.BLUE,0.2f);
//			}

            //kindeditor4.x编辑器中上传图片 返回ke中需要的url和error值 注意：同域中本方法直接返回json格式字符即可
            String referer = request.getHeader("referer");
            if (referer == null) {
                //返回数据
                return responseData(request.getRequestURL().toString().replace(request.getRequestURI(), "") + filePath, 0, "上传成功", response);
            }
            Pattern p = Pattern.compile("([a-z]*:(//[^/?#]+)?)?", Pattern.CASE_INSENSITIVE);
            Matcher mathcer = p.matcher(referer);
            System.out.println("imgk4 referer:" + referer);
            if (mathcer.find()) {
                String callBackPath = mathcer.group();// 请求来源
                JsonObject json = new JsonObject();
                // 编辑器中需要返回完整的路径
                json.addProperty("url", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + filePath);
                json.addProperty("error", 0);
                json.addProperty("message", "上传成功");

                // 同域时直接返回json即可无需redirect
                String url = "redirect:" + callBackPath + "/kindeditor/plugins/image/redirect.html?s=" + URLEncoder.encode(json.toString(), "utf8") + "#" + URLEncoder.encode(json.toString(), "utf8");
                System.out.println("imgk4 ok");
                return url;
            } else {
                //返回数据
                return responseData(filePath, 0, "上传成功", response);
            }

        } catch (Exception e) {
            System.out.println("kindEditorUpload()--error" + e);
            return responseErrorData(response, 2, "系统繁忙，上传失败。");
        }
    }

    public String responseData(String path, int error, String message, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", path);
        map.put("error", error);
        map.put("message", message);
        response.getWriter().write(FastJsonUtil.obj2JsonString(map));
        return null;
    }


    //1.商品系统-选择文件上传-新增
    @RequestMapping(value = "/uploadFileToSys", method = {RequestMethod.POST})
    @Transactional
    public void uploadFileToSys(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String fileSuffix = request.getParameter("fileSuffix");
        String fileId = toString(new Date(), "yyyyMMdd") + System.currentTimeMillis();
        String fileName = fileId + fileSuffix;
        long fileSize = Integer.parseInt(request.getParameter("fileSize").toString());

        System.out.println("服务端文件名:" + fileName);
        System.out.println("服务端文件大小:" + fileSize);

        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取文件路径
        String projectPath = "D://swq//release//static//";
        String filePath = "upload";
        filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;

        InputStream input = null;
        FileOutputStream fos = null;
        try {
            input = request.getInputStream();
            File file = new File(projectPath + filePath);
            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(projectPath + filePath);
            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = input.read(buffer, 0, 1024)) != -1) {
                fos.write(buffer, 0, size);
            }

            //////231122
            //JwtUser sessionUserBean = SessionUtil.getSession();
            String userId = "1";//管理员账号
            ///保存上传文件信息
            //String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
            FileBean fileBean = new FileBean();
            fileBean.setCreateUserId(userId);
            fileBean.setFileId(fileId);
            fileBean.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd") + System.currentTimeMillis());
            int num = fileMapper.insertRecord(fileBean);
            System.out.println("num数值:" + num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile userFile = new UserFile();
            userFile.setUserFileId(fileId);
            userFile.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setUploadTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setCreateUserId(userId);
            userFile.setDeleteFlag(0);
            userFile.setExtendName(ext);
            userFile.setFileId(fileId);
            userFile.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(userId);
            userFileMapper.insert(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile(ext)) {//是图片扩展名内的
                    //   BufferedImage src = uploadFileResult.getBufferedImage();
                    File file1 = new File(projectPath + filePath);
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        //响应信息 json字符串格式
                        Map<String, Object> responseMap = new HashMap<String, Object>();
                        responseMap.put("flag", false);
                        responseMap.put("msg", "文件不存在");
                        //生成响应的json字符串
                        String jsonResponse = JSONObject.toJSONString(responseMap);
                        System.out.println("jsonReponse:" + jsonResponse);
                        ///返回给客户端的数据
                        final String output = jsonResponse;
                        response.setContentLength(output.length());
                        response.getOutputStream().write(output.getBytes());
                        response.getOutputStream().flush();
                        response.getOutputStream().close();
                        ////end-返回给客户端的数据
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.insert(image);
                }
            } catch (Exception e) {
                log.error("生成图片缩略图失败！", e);
            }
            ///end-保存图片的宽度、高度
            //////end-231122*/

            //响应信息 json字符串格式
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", true);
            responseMap.put("userFileId", fileId);//上传文件ID
            //生成响应的json字符串
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        } catch (IOException e) {
            //响应信息 json字符串格式
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", false);
            responseMap.put("errorMsg", e.getMessage());
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (input != null) {
                input.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

    //2.商品系统-上传文件-更新
    @RequestMapping(value = "/uploadFileToSysUpdate", method = {RequestMethod.POST})
    @Transactional
    public void uploadFileToSysUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String fileSuffix = request.getParameter("fileSuffix");
        String fileId = request.getParameter("userFileId");//上一次保存下来的文件名称ID
        String fileName = fileId + fileSuffix;
        long fileSize = Integer.parseInt(request.getParameter("fileSize").toString());
        System.out.println("服务端文件名:" + fileName);
        System.out.println("服务端文件大小:" + fileSize);
        ////旧的系统文件先删除
        FileBean fileBeanDev = fileMapper.selectFileOnlyRecord(fileId);
        if (fileBeanDev != null) {
            String projectPath1 = projectPath + fileBeanDev.getFileUrl();
            File fileDel = new File(projectPath1);
            if (fileDel.delete()) {
                System.out.println("文件删除成功！");
            }
        }
        ////end-旧的系统文件先删除

        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        //构建文件保存路径
        String projectPath = "D://swq//release//static//";
        String filePath = "upload";
        filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;
        //end-构建文件保存路径
        InputStream input = null;
        FileOutputStream fos = null;
        try {
            input = request.getInputStream();
            File file = new File(projectPath + filePath);
            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(projectPath + filePath);
            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = input.read(buffer, 0, 1024)) != -1) {
                fos.write(buffer, 0, size);
            }

            //////231122
            //JwtUser sessionUserBean = SessionUtil.getSession();
            String userId = "1";//管理员账号
            ///保存上传文件信息
            //String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
            FileBean fileBean = new FileBean();
            fileBean.setModifyUserId(userId);
            fileBean.setFileId(fileId);
            fileBean.setModifyTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd") + System.currentTimeMillis());
            int num = fileMapper.updateByFileId(fileBean);
            System.out.println("更新num数值:" + num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile userFile = new UserFile();
            userFile.setUserFileId(fileId);
            userFile.setModifyTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setUploadTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setModifyUserId(userId);
            userFile.setDeleteFlag(0);
            userFile.setExtendName(ext);
            userFile.setFileId(fileId);
            userFile.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(userId);
            userFileMapper.updateByUserFileId(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile(ext)) {//是图片扩展名内的
                    //   BufferedImage src = uploadFileResult.getBufferedImage();
                    File file1 = new File(projectPath + filePath);
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        //响应信息 json字符串格式
                        Map<String, Object> responseMap = new HashMap<String, Object>();
                        responseMap.put("flag", false);
                        responseMap.put("msg", "文件不存在");
                        //生成响应的json字符串
                        String jsonResponse = JSONObject.toJSONString(responseMap);
                        System.out.println("jsonReponse:" + jsonResponse);
                        ///返回给客户端的数据
                        final String output = jsonResponse;
                        response.setContentLength(output.length());
                        response.getOutputStream().write(output.getBytes());
                        response.getOutputStream().flush();
                        response.getOutputStream().close();
                        ////end-返回给客户端的数据
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageId(1l);
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.updateByImageFileId(image);
                }
            } catch (Exception e) {
                log.error("生成图片缩略图失败！", e);
            }
            ///end-保存图片的宽度、高度
            //////end-231122*/

            //响应信息 json字符串格式
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", true);
            responseMap.put("userFileId", fileId);//上传文件ID
            //生成响应的json字符串
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        } catch (IOException e) {
            //响应信息 json字符串格式
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", false);
            responseMap.put("errorMsg", e.getMessage());
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (input != null) {
                input.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    //3.商品系统-批量下载
    @Operation(summary = "商品传值-批量下载文件", description = "商品传值-批量下载文件", tags = {"filetransfer"})
    @RequestMapping(value = "/batchDownloadFileProduct", method = RequestMethod.GET)
    @MyLog(operation = "批量下载文件", module = CURRENT_MODULE)
    @ResponseBody
    public void batchDownloadFile_product(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filesUserFileIds = request.getParameter("userFileIds");
        Cookie[] cookieArr = request.getCookies();
      /*  String token = "";
        if (cookieArr != null) {
            for (Cookie cookie : cookieArr) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }*/
        try {
            String files = filesUserFileIds;
            String[] userFileIdStrs = files.split(",");
            List<String> userFileIds = new ArrayList<>();
            for (String userFileId : userFileIdStrs) {
                UserFile userFile = userFileService.getById(userFileId);
                if (userFile.getIsDir() == 0) {
                    userFileIds.add(userFileId);
                } else {
                    userFile.setUserId("");//swq231122 置空包含全部文件
                    QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                    List<UserFile> userFileList = userFileService.selectUserFileByLikeRightFilePath(qiwenFile.getPath(), userFile.getUserId(), userFile.getUploadType());//swq231120
                    List<String> userFileIds1 = userFileList.stream().map(UserFile::getUserFileId).collect(Collectors.toList());
                    userFileIds.add(userFile.getUserFileId());
                    userFileIds.addAll(userFileIds1);
                }
            }
            UserFile userFile = userFileService.getById(userFileIdStrs[0]);
            response.setContentType("application/force-download");// 设置强制下载不打开
            Date date = new Date();
            String fileName = String.valueOf(date.getTime());
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName + ".zip");// 设置文件名
            filetransferService.downloadUserFileList(response, userFile.getFilePath(), fileName, userFileIds);

            //生成响应的json字符串
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", true);
            responseMap.put("msg", "文件下载成功");
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        } catch (Exception e) {
            //生成响应的json字符串
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("flag", false);
            responseMap.put("msg", "文件下载失败");
            String jsonResponse = JSONObject.toJSONString(responseMap);
            System.out.println("jsonReponse:" + jsonResponse);
            ///返回给客户端的数据
            final String output = jsonResponse;
            response.setContentLength(output.length());
            response.getOutputStream().write(output.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();
            ////end-返回给客户端的数据
        }
    }

    //4.文件夹逐个读取文件示例
    @Operation(summary = "从商品系统批量上传文件", description = "从商品系统批量上传文件-描述", tags = {"filetransfer"})
    @RequestMapping(value = "/getEveryFile", method = {RequestMethod.POST})
    @MyLog(operation = "从商品系统批量上传文件", module = CURRENT_MODULE)
    @Transactional
    public Map<String, Object> getEveryFile(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile[] multipartFile) throws Exception {

        SimpleDateFormat sdfBegin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateBegin = new Date();
        String formattedDateBegin = sdfBegin.format(currentDateBegin);

        //必传
        String id = request.getParameter("id");//商品记录的ID
        String productCode = request.getParameter("productCode");//商品编号
        String childFileType = request.getParameter("childFileType");
        String fileType = "", insertNum = "0";
        //文件类型 1:图片;2:视频
        if (childFileType.equals("1") || childFileType.equals("2") || childFileType.equals("3") || childFileType.equals("4")
                || childFileType.equals("5")) {
            fileType = "1";//1:参考图片;2:网红图;3:商品图;4:站外图;5:对色图;
        } else {
            fileType = "2";//6:主图视频7:网红视频;8:广告视频9:品牌视频10:A+视频 11:3D动画
        }
        String userId = request.getParameter("userId");//上传操作用户

        //可选
        String pictureColor = request.getParameter("pictureColor");
        //平台 1:亚马逊;2:TEMU;3:SHEIN;4:TK;5:沃尔玛;6:独立站
        String platform = request.getParameter("platform");
        //图片分类 1:主副图;2:A+;3:关联图;4:SB广告图；5:SD广告图;6:POST图片;7:线稿图;8:标签图
        String pictureType = request.getParameter("pictureType");
        //规格
        String specifications = request.getParameter("specifications");
        //销售状态 0:在售;1:停售
        String saleStatus = request.getParameter("saleStatus");
        //上传文件ID 文件系统返回
        // String  userFileId="";
        ///////////////////////
        String flag = "";//响应返回值
        // 指定文件夹路径
        //  String folderPath =request.getParameter("folderPath");// "D:\\test";

        JSONObject jsonObject1 = new JSONObject();
        for (int i = 0; i < multipartFile.length; i++) {
            jsonObject1.put("fileName" + i, multipartFile[i].getOriginalFilename());
        }
        System.out.println("上传数量:" + multipartFile.length);
        System.out.println(jsonObject1);
        if (multipartFile.length > 20) {
            //响应
            Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag", false);     //设置Json对象的属性
            jsonObject.put("msg", "目前上传数量" + multipartFile.length + ",批量上传文件数量不能超过20");
            return jsonObject;
        }

        JSONObject jsobj1 = new JSONObject();
        String userFileIds = "", fileSuffixs = "";
        try {
            for (int i = 0; i < multipartFile.length; i++) {
                //获取文件名
                String fileName = multipartFile[i].getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                String fileId = toString(new Date(), "yyMMdd") + System.currentTimeMillis();
                //获取文件路径
                String projectPath = "D://swq//release//static//";
                String filePath = "upload";
                filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;

                //指定本地文件夹存储图片
                File dir = new File(projectPath + filePath);
                if (!dir.getParentFile().exists()) {
                    dir.getParentFile().mkdirs();
                }

                if (multipartFile[i] != null) {
                    System.out.println(multipartFile[i]);
                    //批量上传文件
                    String oriFileName = fileName.substring(0, fileName.lastIndexOf("."));
                    ///判断在系统里面是不是有同名文件,有的改名
                    UserFile userFile = userFileMapper.selectByUserByFileName(oriFileName);
                    if (userFile != null) {
                        int sjNum = (int) (Math.random() * 100 + 1);
                        oriFileName = oriFileName + sjNum;
                    }
                    ///end-判断在系统里面是不是有同名文件

                    uploadFileAddT(multipartFile[i], fileId, ext, oriFileName);
                    if (userFileIds.equals("")) {
                        userFileIds = fileId;
                        fileSuffixs = "." + ext;
                    } else {
                        userFileIds = userFileIds + "," + fileId;
                        fileSuffixs = fileSuffixs + "," + "." + ext;
                    }
                    jsobj1.put("userFileIds" + i, fileId.trim() + "." + ext.trim());
                }
            }
            jsobj1.put("recordNum", multipartFile.length + "");
            System.out.println("文件组合:" + userFileIds);
            System.out.println("后缀组合:" + fileSuffixs);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (!userFileIds.equals("")) {
                jsobj1.put("id", id.trim());
                if (productCode != null)
                    jsobj1.put("productCode", productCode.trim());
                else
                    jsobj1.put("productCode", "");

                if (fileType != null)
                    jsobj1.put("fileType", fileType.trim());
                else
                    jsobj1.put("fileType", "");

                if (childFileType != null)
                    jsobj1.put("childFileType", childFileType.trim());
                else
                    jsobj1.put("childFileType", "");

                if (pictureColor != null)
                    jsobj1.put("pictureColor", pictureColor.trim());
                else
                    jsobj1.put("pictureColor", "");

                if (platform != null)
                    jsobj1.put("platform", platform.trim());
                else
                    jsobj1.put("platform", "");
                if (pictureType != null)
                    jsobj1.put("pictureType", pictureType.trim());
                else
                    jsobj1.put("pictureType", "");
                if (specifications != null)
                    jsobj1.put("specifications", specifications.trim());
                else
                    jsobj1.put("specifications", "");
                if (saleStatus != null)
                    jsobj1.put("saleStatus", saleStatus.trim());
                else
                    jsobj1.put("saleStatus", "");
                if (userId != null)
                    jsobj1.put("userId", userId.trim());
                else
                    jsobj1.put("userId", "");

                String returnStr = post(jsobj1, "http://110.81.207.46:8081/upload/fileMore");
                //String returnStr = post(jsobj1, "http://127.0.0.1:8081/upload/fileMore");
                Map<String, Object> map = json2Map(returnStr.toString());
                flag = map.get("flag").toString();
                insertNum = map.get("insertNum").toString();

                if (flag.equals("true")) {//返回插入数据成功,给前端返回结果
                    ///swq231129写入操作日志
                    String ipAddress = request.getRemoteAddr();
                    OperationLogBean operationlogBean = new OperationLogBean();
                    operationlogBean.setDetail("商品编号:" + productCode + "已经成功批量上传" + insertNum + "文件.");
                    operationlogBean.setOperation("批量上传文件");
                    operationlogBean.setRequestMethod("Get");
                    operationlogBean.setRequestURI("/filetransfer/getEveryFile");
                    operationlogBean.setResult("成功");
                    operationlogBean.setTerminal(ipAddress);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date currentDate = new Date();
                    String formattedDate = sdf.format(currentDate);
                    operationlogBean.setTime(formattedDate);
                    operationlogBean.setUserId("商品系统用户ID:" + userId);
                    operationlogBean.setSource("文件批量上传接口");
                    operationLogService.insertOperationLog(operationlogBean);
                    ///end-写入操作日志
                    //响应
                    Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
                    jsonObject.put("flag", true);     //设置Json对象的属性
                    jsonObject.put("msg", "商品编号:" + productCode + "已经成功批量上传" + insertNum + "文件.");

                    // 获取时间戳
                    long timestamp1 = currentDateBegin.getTime();
                    long timestamp2 = currentDate.getTime();
                    // 计算两个时间戳的差值
                    long diff = Math.abs(timestamp1 - timestamp2);
                    long seconds = (diff / 1000) % 60;
                    System.out.println("上传开始时间:" + formattedDateBegin + ",结束时间:" + formattedDate + ",耗时秒数:" + seconds);
                    return jsonObject;
                } else {
                    //返回失败-删除已上传的记录
                    String userFileIdArr[] = userFileIds.split(",");
                    for (int i = 0; i < userFileIdArr.length; i++) {
                        String userFileId = userFileIdArr[i].toString();
                        ////逐一删除
                        FileBean fileBean = fileMapper.selectFileOnlyRecord(userFileId);
                        if (fileBean != null) {
                            String projectPath1 = projectPath + fileBean.getFileUrl();
                            File file = new File(projectPath1);
                            if (file.delete()) {
                                System.out.println("失败1:文件删除成功！");
                                int num1 = userFileMapper.deleteByFileId(userFileId);//删除记录
                                int num2 = imageMapper.deleteByFileId(userFileId);
                                int num3 = fileMapper.deleteByFileId(userFileId);
                                System.out.println(num1 + "," + num2 + "," + num3);
                            } else {
                                System.out.println("失败1:文件删除失败！");
                            }
                        }
                        ////逐一删除
                    }
                    //end-返回失败-删除已上传的记录

                    ///swq231129写入操作日志
                    String ipAddress = request.getRemoteAddr();
                    OperationLogBean operationlogBean = new OperationLogBean();
                    operationlogBean.setDetail("商品编号:" + productCode + "批量上传失败" + insertNum + "个文件.");
                    operationlogBean.setOperation("批量上传文件");
                    operationlogBean.setRequestMethod("Get");
                    operationlogBean.setRequestURI("/filetransfer/getEveryFile");
                    operationlogBean.setResult("失败");
                    operationlogBean.setTerminal(ipAddress);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date currentDate = new Date();
                    String formattedDate = sdf.format(currentDate);
                    operationlogBean.setTime(formattedDate);
                    operationlogBean.setUserId("商品系统用户ID:" + userId);
                    operationlogBean.setSource("文件批量上传接口");
                    operationLogService.insertOperationLog(operationlogBean);
                    ///end-写入操作日志

                    //响应
                    Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
                    jsonObject.put("flag", false);     //设置Json对象的属性
                    jsonObject.put("msg", "批量上传失败");
                    return jsonObject;
                }
            } else {
                Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
                jsonObject.put("flag", false);     //设置Json对象的属性
                jsonObject.put("msg", "批量上传失败,并未生成文件.");
                return jsonObject;
            }
        } catch (Exception e) {
            ///swq231129写入操作日志
            String ipAddress = request.getRemoteAddr();
            OperationLogBean operationlogBean = new OperationLogBean();
            operationlogBean.setDetail("商品编号:" + productCode + "批量上传失败,错误:" + e.getMessage());
            operationlogBean.setOperation("批量上传文件");
            operationlogBean.setRequestMethod("Get");
            operationlogBean.setRequestURI("/filetransfer/getEveryFile");
            operationlogBean.setResult("失败");
            operationlogBean.setTerminal(ipAddress);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentDate = new Date();
            String formattedDate = sdf.format(currentDate);
            operationlogBean.setTime(formattedDate);
            operationlogBean.setUserId("商品系统用户ID:" + userId);
            operationlogBean.setSource("文件批量上传接口");
            operationLogService.insertOperationLog(operationlogBean);
            ///end-写入操作日志
            //返回失败-删除已上传的记录
            String userFileIdArr[] = userFileIds.split(",");
            for (int i = 0; i < userFileIdArr.length; i++) {
                String userFileId = userFileIdArr[i].toString();
                ////逐一删除
                FileBean fileBean = fileMapper.selectFileOnlyRecord(userFileId);
                if (fileBean != null) {
                    String projectPath1 = projectPath + fileBean.getFileUrl();
                    File file = new File(projectPath1);
                    if (file.delete()) {
                        System.out.println("异常:文件删除成功！");
                        int num1 = userFileMapper.deleteByFileId(userFileId);//删除记录
                        int num2 = imageMapper.deleteByFileId(userFileId);
                        int num3 = fileMapper.deleteByFileId(userFileId);
                        System.out.println(num1 + "," + num2 + "," + num3);
                    } else {
                        System.out.println("异常:文件删除失败！");
                    }
                }
                ////逐一删除
            }
            //end-返回失败-删除已上传的记录

            //响应
            Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag", false);     //设置Json对象的属性
            jsonObject.put("msg", "批量上传失败,错误:" + e.getMessage());
            return jsonObject;
        }

    }

    //4.1递归调用
 /*  public  void xunHuan(File folder) throws Exception {
       ////
       // 获取文件夹中的所有文件
       File[] files = folder.listFiles();
       // 遍历文件数组
       for (File file : files) {
           // 检查是否为文件
           if (file.isFile()) {
               System.out.println(file.getPath());
               String fileSuffix = file.getPath().substring(file.getPath().lastIndexOf("."));
               String userFileId=uploadFileAdd(file.getPath(),fileSuffix);
               if(userFileIds.equals("")) {
                   userFileIds = userFileId;
                   fileSuffixs=fileSuffix;
               }
               else {
                   userFileIds=userFileIds+","+userFileId;
                   fileSuffixs=fileSuffixs+","+fileSuffix;
               }
           }
           else { ///如果还是文件夹
               if(file.exists() && file.isDirectory())
               {
                   xunHuan(file);
               }
           }
       }
       /////
   }*/

    ///4.2
    public static String post(JSONObject json, String url) {
        String result = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "appliction/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + "\n");
            }
            in.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        System.out.println("result==" + result);
        return result;
    }


    //4.3逐个插入
    public String uploadFileAdd(FileInputStream fileInputStream, String fileId, String fileSuffix) throws Exception {
        // String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
        String fileName = fileId + "." + fileSuffix;
        long fileSize = 0;

        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取文件路径
        String projectPath = "D://swq//release//static//";
        String filePath = "upload";
        filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;
        try {
            File file = new File(projectPath + filePath);
            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            String targetFile = projectPath + filePath;
            try {
                fis = fileInputStream;
                fos = new FileOutputStream(targetFile);
                // 从源文件中读取数据
                int data;
                while ((data = fis.read()) != -1) {
                    // 将数据写入目标文件中
                    fos.write(data);
                }
                System.out.println("文件保存成功！");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }

            File fileExist = new File(projectPath + filePath);
            if (fileExist.exists()) fileSize = fileExist.length();
            System.out.println("服务端文件名:" + fileName);
            System.out.println("服务端文件大小:" + fileSize);

            String userId = "1";//管理员账号
            ///保存上传文件信息
            FileBean fileBean = new FileBean();
            fileBean.setCreateUserId(userId);
            fileBean.setFileId(fileId);
            fileBean.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd") + System.currentTimeMillis());
            int num = fileMapper.insertRecord(fileBean);
            System.out.println("num数值:" + num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile userFile = new UserFile();
            userFile.setUserFileId(fileId);
            userFile.setCreateTime(toString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            userFile.setUploadTime(toString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            userFile.setCreateUserId(userId);
            userFile.setDeleteFlag(0);
            userFile.setExtendName(ext);
            userFile.setFileId(fileId);
            userFile.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(userId);
            userFileMapper.insert(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile(ext)) {//是图片扩展名内的
                    File file1 = new File(projectPath + filePath);
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        //响应信息 json字符串格式
                        Map<String, Object> responseMap = new HashMap<String, Object>();
                        responseMap.put("flag", false);
                        responseMap.put("msg", "文件不存在");
                        //生成响应的json字符串
                        String jsonResponse = JSONObject.toJSONString(responseMap);
                        System.out.println("jsonReponse:" + jsonResponse);
                    /*    ///返回给客户端的数据
                        final String output =jsonResponse;
                        response.setContentLength(output.length());
                        response.getOutputStream().write(output.getBytes());
                        response.getOutputStream().flush();
                        response.getOutputStream().close();
                        ////end-返回给客户端的数据*/
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.insert(image);
                }
            } catch (Exception e) {
                log.error("生成图片缩略图失败！", e);
                return "0";
            }
            ///end-保存图片的宽度、高度
        } catch (Exception e) {
            return "0";

        }
        return fileId;
    }

    ///swq4.3.1
    public String uploadFileAddT(MultipartFile imgFile, String fileId, String fileSuffix, String oriFileName) throws Exception {
        // String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
        String fileName = fileId + "." + fileSuffix;
        long fileSize = 0;

        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取文件路径
        String projectPath = "D://swq//release//static//";
        String filePath = "upload";
        filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;
        try {
            File file = new File(projectPath + filePath);
            //如果目录不存在，则创建
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            imgFile.transferTo(file);

            File fileExist = new File(projectPath + filePath);
            if (fileExist.exists()) fileSize = fileExist.length();
            System.out.println("服务端文件名:" + fileName);
            System.out.println("服务端文件大小:" + fileSize);

            String userId = "1";//管理员账号
            ///保存上传文件信息
            FileBean fileBean = new FileBean();
            fileBean.setCreateUserId(userId);
            fileBean.setFileId(fileId);
            fileBean.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd") + System.currentTimeMillis());
            int num = fileMapper.insertRecord(fileBean);
            System.out.println("num数值:" + num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile userFile = new UserFile();
            userFile.setUserFileId(fileId);
            userFile.setCreateTime(toString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            userFile.setUploadTime(toString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            userFile.setCreateUserId(userId);
            userFile.setDeleteFlag(0);
            userFile.setExtendName(ext);
            userFile.setFileId(fileId);
            userFile.setFileName(oriFileName);
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(userId);
            userFileMapper.insert(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile(ext)) {//是图片扩展名内的
                    File file1 = new File(projectPath + filePath);
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        //响应信息 json字符串格式
                        Map<String, Object> responseMap = new HashMap<String, Object>();
                        responseMap.put("flag", false);
                        responseMap.put("msg", "文件不存在");
                        //生成响应的json字符串
                        String jsonResponse = JSONObject.toJSONString(responseMap);
                        System.out.println("jsonReponse:" + jsonResponse);
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.insert(image);
                }
            } catch (Exception e) {
                log.error("生成图片缩略图失败！", e);
                return "0";
            }
            ///end-保存图片的宽度、高度
        } catch (Exception e) {
            return "0";

        }
        return fileId;
    }


    ///4.4转换
    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if (jsonStr != null && !"".equals(jsonStr)) {
            //最外层解析
            JSONObject json = JSONObject.parseObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<Object> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = (JSONObject) it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        } else {
            return null;
        }
    }


    @RequestMapping(value = "/getUploadFile", method = {RequestMethod.GET, RequestMethod.POST})
    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Part folderPart = request.getPart("folder");
            InputStream folderInputStream = folderPart.getInputStream();

            // 使用folderInputStream来读取文件夹中的文件
            // 可以使用Java的IO API来实现这个功能

            // 关闭输入流
            folderInputStream.close();
        }
    }


    ///5.商品系统促销管理上传图片

    @Operation(summary = "商品系统促销管理上传图片 ", description = "商品系统促销管理上传图片 ", tags = {"filetransfer"})
    @RequestMapping(value = "/uploadPromotionPicture", method = {RequestMethod.POST})
    @MyLog(operation = "从商品系统批量上传文件", module = CURRENT_MODULE)
    @Transactional
    public Map<String, Object> uploadPromotionPicture(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile[] multipartFile) throws Exception {

       // SimpleDateFormat sdfBegin = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        JSONObject jsonObject1 = new JSONObject();
        for (int i = 0; i < multipartFile.length; i++) {
            jsonObject1.put("fileName" + i, multipartFile[i].getOriginalFilename());
        }
        System.out.println("上传数量:" + multipartFile.length);
        System.out.println(jsonObject1);
        if (multipartFile.length > 20) {
            //响应
            Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag", false);     //设置Json对象的属性
            jsonObject.put("msg", "目前上传数量" + multipartFile.length + ",批量上传文件数量不能超过20");
            return jsonObject;
        }

        JSONObject jsobj1 = new JSONObject();
        String userFileIds = "", fileSuffixs = "";
        try {
            for (int i = 0; i < multipartFile.length; i++) {
                //获取文件名
                String fileName = multipartFile[i].getOriginalFilename();
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                int seed = (int) System.currentTimeMillis();
                int randomInt = new Random(seed).nextInt();
                String fileId = toString(new Date(), "yyMMdd") + randomInt;
                //获取文件路径
                String projectPath = "D://swq//release//static//";
                String filePath = "upload";
                filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;

                //指定本地文件夹存储图片
                File dir = new File(projectPath + filePath);
                if (!dir.getParentFile().exists()) {
                    dir.getParentFile().mkdirs();
                }

                if (multipartFile[i] != null) {
                    System.out.println(multipartFile[i]);
                    //批量上传文件
                    String oriFileName = fileName.substring(0, fileName.lastIndexOf("."));
                    ///判断在系统里面是不是有同名文件,有的改名
                    UserFile userFile = userFileMapper.selectByUserByFileName(oriFileName);
                    if (userFile != null) {
                        int sjNum = (int) (Math.random() * 100 + 1);
                        oriFileName = oriFileName + sjNum;
                    }
                    ///end-判断在系统里面是不是有同名文件

                    uploadFileAddT(multipartFile[i], fileId, ext, oriFileName);
                    if (userFileIds.equals("")) {
                        userFileIds = fileId;
                        fileSuffixs = "." + ext;
                    } else {
                        userFileIds = userFileIds + "," + fileId;
                        fileSuffixs = fileSuffixs + "," + "." + ext;
                    }
                    jsobj1.put("userFileNames" + i, fileId.trim() + "." + ext.trim());
                }
            }
            jsobj1.put("recordNum", multipartFile.length + "");
            jsobj1.put("userFileIds",userFileIds);
            jsobj1.put("code",200);
            jsobj1.put("msg","成功上传"+multipartFile.length+"个文件");
            System.out.println("文件组合:" + userFileIds);
            System.out.println("后缀组合:" + fileSuffixs);
        } catch (Exception e) {
            jsobj1.put("code",500);
            jsobj1.put("msg","文件上传失败.");
            e.printStackTrace();

        }
     return  jsobj1;
    }


        ////////////////////////////231123以下是走本地系统 下载、删除文件夹/////////////////////////////////////////////
    //2.文件从其他网址下载图片到本地接口
    @RequestMapping(value="/downloadUrlPicture",method={RequestMethod.GET})
    @Transactional
    public JSONObject downloadUrlPicture(HttpServletRequest request,String url) throws Exception {
        String storeUserId="1";//全部挂到管理员下面 1:配置给其他账号查看
        JSONObject json = new JSONObject();
        String strs[]={url};
        for(int i=0;i<strs.length;i++){
            String durl=strs[i];
            String ext="jpg";
            String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
            //获取文件路径
            //String projectPath ="D:/爱斯奇/图片网盘/奇文网盘/qiwen-file/qiwen-file/target/classes/static";
            String filePath = getPath(request,ext,"");
            File file1= new File(projectPath+filePath);
            //如果目录不存在，则创建
            if(!file1.getParentFile().exists()){
                file1.getParentFile().mkdirs();
            }
            download( durl, projectPath+filePath);
            System.out.println(i);

            //  JwtUser sessionUserBean = SessionUtil.getSession();
            long fileSize = file1.length() / 1024;
            ///保存上传文件信息
            FileBean fileBean = new FileBean();
            fileBean.setCreateUserId(storeUserId);//1:管理员
            fileBean.setFileId(fileId);
            fileBean.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd")+System.currentTimeMillis());
            int num= fileMapper.insertRecord(fileBean);
            System.out.println("num数值:"+num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile  userFile=new UserFile();
            userFile.setUserFileId(toString(new Date(), "yyyyMMdd")+System.currentTimeMillis());
            userFile.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setCreateUserId(storeUserId);//1:自己;
            userFile.setDeleteFlag(0);
            userFile.setExtendName("jpg");
            userFile.setFileId(fileId);
            userFile.setFileName(fileId);//文件名同ID
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(storeUserId);//1:自己
            userFileMapper.insert(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile("jpg")) {//是图片扩展名内的
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        json.put("value","fail");
                        json.put("msg","文件不存在");
                        return  json;
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.insert(image);
                }
            } catch (Exception e) {
                log.error("生成图片缩略图失败！", e);
            }
            ///end-保存图片的宽度、高度
        }
        json.put("value","success");
        json.put("msg","文件下载成功.");
        return  json;
    }

    //3.删除文件接口
    @RequestMapping(value="/deletePicture",method={RequestMethod.DELETE})
    @Transactional
    public JSONObject deletePicture(HttpServletRequest request,String fileId) throws Exception {
        JSONObject json = new JSONObject();
        FileBean fileBean=fileMapper.selectFileOnlyRecord(fileId);
        if(fileBean!=null) {
            String projectPath1= projectPath+fileBean.getFileUrl();
            File file = new File(projectPath1);
            if (file.delete()) {
                System.out.println("文件删除成功！");
                int num1=userFileMapper.deleteByFileId(fileId);//删除记录
                int num2=imageMapper.deleteByFileId(fileId);
                int num3=fileMapper.deleteByFileId(fileId);
                System.out.println(num1+","+num2+","+num3);
                json.put("value","success");
                json.put("msg","文件删除成功");
                return  json;
            } else {
                System.out.println("文件删除失败！");
                json.put("value","fail");
                json.put("msg","文件删除失败");
                return  json;
            }
        }
        else {
            json.put("value","fail");
            json.put("msg","记录不存在");
            return  json;
        }
    }

    public static void download(String durl,String fileName) throws Exception {
        //定义一个URL对象，就是你想下载的图片的URL地址
        URL url = new URL(durl);
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream is = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(is);
        //创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
        File imageFile = new File(fileName);
        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流，释放资源
        outStream.close();
    }
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /////////////swq20231125-文件读取文件示例//////////////////

}
